package com.yuandian.business.monitor.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.api.business_monitor.po.SqlAnalysisParams;
import com.yuandian.api.business_monitor.vo.SqlAnalysisDetailsVo;
import com.yuandian.api.business_monitor.vo.SqlAnalysisVo;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.business.monitor.mapper.SqlAnalysisMapper;
import com.yuandian.business.monitor.service.ISqlAnalysisService;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.YDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * sql分析
 *
 * @author zhoutian
 * @date 2020/8/20 11:33
 */
@Service
public class SqlAnalysisServiceImpl implements ISqlAnalysisService {

    @Autowired
	SqlAnalysisMapper sqlAnalysisMapper;

    /**
     * SQL分析图表数据查询
     *
     * @return Result
     */
    @Override
    public R<List<SqlAnalysisVo>> getSqlAnalysisList(SqlAnalysisParams params) {
        List<SqlAnalysisVo> list = new ArrayList<>();
            Date newDate = YDateUtil.parseDate(params.getCurrentTime());
            Map<String, String> startTime = YDateUtil.getTimePiece(newDate, params.getTimePiece(), params.getTimePiece());
            params.setStartTime(startTime.get("startTime"));
            params.setEndTime(startTime.get("endTime"));
            String tableName = "ads_busi_sql_analysis_m";
            Integer count = sqlAnalysisMapper.getCount(params, tableName);
            if (count > 0) {
                list = sqlAnalysisMapper.getSqlAnalysisList(params, tableName);
            }

        return R.ok(list);
    }

    /**
     * SQL分析详情
     *
     * @param params 参数
     * @return PageDataInfo
     */
    @Override
    public PageDataInfo getSqlAnalysisDetails(SqlAnalysisParams params) {

        if (StringUtils.isBlank(params.getOrderByColumn())){
            params.setOrderByColumn("dealTime");
            params.setIsAsc("desc");
        }
		Date currentTime = YDateUtil.parseDate(params.getCurrentTime());
		Map<String, String> startTime = YDateUtil.getTimePiece(currentTime, params.getTimePiece(), params.getTimePiece());
	    Page<SqlAnalysisDetailsVo> page = new Page<>(params.getPageNum(), params.getPageSize());
	    List<SqlAnalysisDetailsVo> list = sqlAnalysisMapper.getSqlAnalysisDetail(
				  params,page,startTime.get("startTime"),
				  startTime.get("endTime"),params.getBussType());

        return new PageDataInfo(page, list);
    }

}
